package com.desktopmng.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.hibernate.Hibernate;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;

import com.desktopmng.core.Constants;
import com.desktopmng.core.ServiceManager;
import com.desktopmng.service.HibernateEntityDao;
import com.desktopmng.core.support.Pager;
import com.desktopmng.core.DataBean;
import com.desktopmng.core.DesktopBean;
import com.desktopmng.core.DesktopStoredProcedure;
import com.desktopmng.core.SystemMsgBean;
import com.desktopmng.orm.DesktopContent;
import com.desktopmng.exception.JFossException;

@SuppressWarnings({"unchecked","rawtypes"})
public class DesktopContentManager extends HibernateEntityDao<DesktopContent> {

	/**
	 * Description: 新增个人桌面内容
	 * 
	 * @param desktopContent
	 *            个人桌面内容对象
	 * @return 操作标记
	 * @throws JFossException
	 */
	public String addDesktopContent(DesktopContent desktopContent)
			throws JFossException {

		String retStr = "true";
		try {
			desktopContent.setId(null);
			this.save(desktopContent);
		} catch (Exception e) {

			throw new JFossException("", e);
		}
		return retStr;

	}

	/**
	 * Description: 修改个人桌面内容
	 * 
	 * @param desktopContent
	 *            个人桌面内容对象
	 * @return 操作标记
	 * @throws JFossException
	 */
	public String updateDesktopContent(DesktopContent desktopContent)
			throws JFossException {
		String retStr = "true";
		try {
			this.getHibernateTemplate().update(desktopContent);
		} catch (Exception e) {

			throw new JFossException("", e);
		}
		return retStr;
	}

	/**
	 * Description: 删除个人桌面内容
	 * 
	 * @param desktopContentId
	 *            个人桌面内容对象Id
	 * @return 操作标记
	 * @throws JFossException
	 */
	public String deleteDesktopContent(Long desktopContentId)
			throws JFossException {
		String retStr = "true";
		try {
			if (null != desktopContentId) {

				this.removeById(DesktopContent.class, desktopContentId);
			}

		} catch (Exception e) {

			throw new JFossException("", e);
		}
		return retStr;
	}

	/**
	 * Description: 查看个人桌面内容对象
	 * 
	 * @param desktopContentId
	 *            个人桌面内容对象Id
	 * @return 个人桌面内容对象
	 * @throws JFossException
	 */
	public DesktopContent findDesktopContentById(Long desktopContentId)
			throws JFossException {

		try {
			if (null != desktopContentId) {
				return (DesktopContent) getHibernateTemplate().get(DesktopContent.class, desktopContentId);
			} else {
				return null;
			}
		} catch (Exception e) {

			throw new JFossException("", e);
		}

	}

	/**
	 * Description: 条件查询个人桌面内容库
	 * 
	 * 条件参数列表，为空时，返回全部个人桌面内容库列表
	 * 
	 * @param prop
	 *            条件参数表，key值对应告警信息，告警位置，设备类型，提供者，记录时间一项或多项
	 * @return 封装个人桌面内容库对象的列表
	 * @throws JFossException
	 */
	public List findDesktopContentByCondition(Properties prop)
			throws JFossException {
		List list = null;
		try {

			String hql = "select p from DesktopContent p where 1=1";
			List paramList = new ArrayList();
			if (null != prop && prop.size() > 0) {
				String dstcName = prop.getProperty("dstcName");
				if (StringUtils.isNotBlank(dstcName)) {
					hql += " and p.dstcName like ?";
					paramList.add("%" + dstcName + "%");
				}
				String posRows = prop.getProperty("posRows");
				if (StringUtils.isNotBlank(posRows)) {
					hql += " and p.posRows = ?";
					paramList.add(new Integer(posRows));
				}
				String posCols = prop.getProperty("posCols");
				if (StringUtils.isNotBlank(posCols)) {
					hql += " and p.posCols = ?";
					paramList.add(new Integer(posCols));
				}
				String status = prop.getProperty("status");
				if (StringUtils.isNotBlank(status)) {
					hql += " and p.status = ?";
					paramList.add(status);
				}
				String resourceName = prop.getProperty("resourceName");
				if (StringUtils.isNotBlank(resourceName)) {
					hql += " and p.resourceName = ?";
					paramList.add(resourceName);
				}
				String id = prop.getProperty("id");
				if (StringUtils.isNotBlank(id)) {
					hql += " and p.id = ?";
					paramList.add(new Long(id));
				}

			}
			hql += " order by p.posRows asc,p.posCols asc";
			list = this.find(hql, paramList.toArray());
			return list;
		} catch (Exception e) {

			throw new JFossException("", e);
		}

	}

	/**
	 * Description: 根据查询条件获取个人桌面内容库对象列表,分页查询
	 * 
	 * @param prop
	 *            查询条件
	 * @param pageNum
	 *            页码
	 * @param pageSize
	 *            页数据量
	 * @return 个人桌面内容库对象列表分页对象
	 * @throws JFossException
	 */
	public Pager findDesktopContentByCondition(Properties prop, int pageNum,
			int pageSize) throws JFossException {
		Pager page = null;
		try {

			String hql = "select p from DesktopContent p where 1=1";
			List paramList = new ArrayList();
			if (null != prop && prop.size() > 0) {
				String dstcName = prop.getProperty("dstcName");
				if (StringUtils.isNotBlank(dstcName)) {
					hql += " and p.dstcName like ?";
					paramList.add("%" + dstcName + "%");
				}
				String posRows = prop.getProperty("posRows");
				if (StringUtils.isNotBlank(posRows)) {
					hql += " and p.posRows = ?";
					paramList.add(new Integer(posRows));
				}
				String posCols = prop.getProperty("posCols");
				if (StringUtils.isNotBlank(posCols)) {
					hql += " and p.posCols = ?";
					paramList.add(new Integer(posCols));
				}
				String status = prop.getProperty("status");
				if (StringUtils.isNotBlank(status)) {
					hql += " and p.status = ?";
					paramList.add(status);
				}
				String resourceName = prop.getProperty("resourceName");
				if (StringUtils.isNotBlank(resourceName)) {
					hql += " and p.resourceName = ?";
					paramList.add(resourceName);
				}
			}
			hql += " order by p.posRows asc,p.posCols asc";
			page = this.pagedQuery(hql, pageNum, pageSize, paramList.toArray());

		} catch (Exception e) {

			throw new JFossException("", e);
		}
		return page;
	}

	/**
	 * Description: 根据个人桌面内容Id获取显示内容对象
	 * 
	 * @param id
	 *            个人桌面内容Id
	 * @param userId
	 *            用户Id
	 * @return 个人桌面显示内容对象
	 * @throws JFossException
	 */
	public DesktopBean findDesktopBeanByDCId(Long id, Long userId)
			throws JFossException {
		DesktopBean obj = new DesktopBean();
		try {
			DesktopContent dc = this.findDesktopContentById(id);
			if (null != dc) {
				String ds = dc.getDataSource();
				List list = new ArrayList();
				if (StringUtils.isNotBlank(ds)) {
					if (Constants.DS_SQL.equals(ds)) {
						// 执行sql语句
						Properties prop = new Properties();
						String dataInfo = dc.getDataInfo();
						if (StringUtils.isNotBlank(dataInfo)) {
							prop.setProperty("sql", dc.getDataInfo());
							String count = "";
							if (null != dc.getDataCount()) {
								count = dc.getDataCount().toString();
							}
							// 设置查询条件参数
							String params = dc.getParams();
							List paramList = getParamList(params, userId);
							prop.put("params", paramList.toArray());
							list = this.findDataByCondition(prop, "0", count);
						}
					} else if (Constants.DS_SERVICE.equals(ds)) {

					} else if (Constants.DS_PROC.equals(ds)) {
						// 执行存储过程
						String dataInfo = dc.getDataInfo();
						if (StringUtils.isNotBlank(dataInfo)) {
							DesktopStoredProcedure dsp = new DesktopStoredProcedure(
									ServiceManager.getDataSource());
							dsp.setSql(dataInfo);
							// 设置查询条件参数
							String params = dc.getParams();
							if (StringUtils.isNotBlank(params)) {
								String[] param = params.split(",");
								if (null != param && param.length > 0) {
									for (int i = 0; i < param.length; i++) {
										if (Constants.PARAM_USERID
												.equals(param[i].toLowerCase())) {
											dsp
													.setVarcharParam(Constants.PARAM_USERID);
											dsp.setValue(
													Constants.PARAM_USERID,
													String.valueOf(userId));
										}
									}
								}
							}
							Map result = dsp.execute();
							if (null != result) {
								list = (List) result.get("data");
							}
						}
					}
				}
				obj.setId(dc.getId());
				obj.setLinkUrl(dc.getLinkUrl());
				obj.setDivId(dc.getDivId());
				obj.setDisplayType(dc.getDisplayType());
				obj.setList(list);
			}
		} catch (Exception e) {

			throw new JFossException("", e);
		}
		return obj;
	}

	/**
	 * Description: 获取系统信息数据统计列表
	 * 
	 * @param id
	 *            个人桌面内容Id
	 * @param userId
	 *            用户Id
	 * @return 系统信息数据统计列表
	 * @throws JFossException
	 */
	public List findSystemMsgStatList(Long id, Long userId)
			throws JFossException {
		List list = null;
		try {
			DesktopContent dc = this.findDesktopContentByDesktopContentId(id);
			if (null != dc) {
				Properties prop = new Properties();
				prop.setProperty("dstcId", String.valueOf(id));
				prop.setProperty("status", Constants.STATUS_VALID);
				String dataCount = "";
				if (null != dc.getDataCount()) {
					dataCount = dc.getDataCount().toString();
				}
				list = this.findSystemMsgByCondition(prop, "0", dataCount);
				if (null != list && list.size() > 0) {
					for (int i = 0; i < list.size(); i++) {
						SystemMsgBean obj = (SystemMsgBean) list.get(i);
						if (null != obj) {
							String ds = obj.getDataSource();
							if (StringUtils.isNotBlank(ds)) {
								if (Constants.DS_SQL.equals(ds)) {
									// 执行Sql语句
									String strSql = obj.getStatSql();
									if (StringUtils.isNotBlank(strSql)) {
										String params = obj.getParams();
										List paramList = getParamList(params,
												userId);
										String count = this
												.findMsgStatByCondition(strSql,
														paramList.toArray());
										obj.setCount(count);
									}
								} else if (Constants.DS_SERVICE.equals(ds)) {

								} else if (Constants.DS_PROC.equals(ds)) {
									// 执行存储过程
									String strSql = obj.getStatSql();
									if (StringUtils.isNotBlank(strSql)) {
										obj.setCount("0");
										DesktopStoredProcedure dsp = new DesktopStoredProcedure(
												ServiceManager.getDataSource());
										dsp.setSql(strSql);
										// 设置查询条件参数
										String params = obj.getParams();
										if (StringUtils.isNotBlank(params)) {
											String[] param = params.split(",");
											if (null != param
													&& param.length > 0) {
												for (int j = 0; j < param.length; j++) {
													if (Constants.PARAM_USERID
															.equals(param[j]
																	.toLowerCase())) {
														dsp
																.setVarcharParam(Constants.PARAM_USERID);
														dsp
																.setValue(
																		Constants.PARAM_USERID,
																		String
																				.valueOf(userId));
													}
												}
											}
										}
										Map result = dsp.execute();
										if (null != result) {
											List tList = (List) result
													.get("data");
											if (null != tList
													&& tList.size() > 0) {
												DataBean dataBean = (DataBean) tList
														.get(0);
												if (null != dataBean) {
													obj.setCount(dataBean
															.getName());
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		} catch (Exception e) {
			throw new JFossException("统计系统消息各类数据出错", e);
		}
		return list;
	}

	/**
	 * Description: 根据参数名称和用户ID生成参数值列表
	 * 
	 * @param params
	 *            参数名称，以“,”隔开
	 * @param userId
	 *            用户Id
	 * @return 参数值列表
	 */
	private List getParamList(String params, Long userId) {
		List paramList = new ArrayList();
		if (StringUtils.isNotBlank(params)) {
			String[] param = params.split(",");
			if (null != param && param.length > 0) {
				for (int i = 0; i < param.length; i++) {
					if (Constants.PARAM_USERID.equals(param[i].toLowerCase())) {
						paramList.add(userId);
					} else if (Constants.PARAM_SYSDATE.equals(param[i]
							.toLowerCase())) {
						Timestamp ts = new Timestamp(new Date().getTime());
						paramList.add(ts);
					}
				}
			}
		}
		return paramList;
	}

	/**
	 * Description: 根据查询条件获取个人桌面显示的数据列表
	 * 
	 * @param prop
	 *            查询条件
	 * @param pageNum
	 *            页码
	 * @param pageSize
	 *            页数据量
	 * @return 封装了显示数据对象的列表
	 */
	public List findDataByCondition(Properties prop, String pageNum,
			String pageSize) throws JFossException {
		List list = null;
		if (null != prop && prop.size() > 0) {
			String sql = prop.getProperty("sql");
			if (StringUtils.isNotBlank(sql)) {
				Object[] params = (Object[]) prop.get("params");
				SQLQuery query = (SQLQuery) createSQLQuery(sql, params);
				query.addScalar("id", Hibernate.STRING);
				query.addScalar("name", Hibernate.STRING);
				query.addScalar("type", Hibernate.STRING);
				query.setResultTransformer(Transformers
						.aliasToBean(DataBean.class));
				query.setFirstResult(NumberUtils.toInt(pageNum, 0));
				query.setMaxResults(NumberUtils.toInt(pageSize, 10));
				list = query.list();
			}
		}
		return list;
	}

	/**
	 * Description: 根据个人桌面内容Id获取个人桌面内容对象
	 * 
	 * @param desktopContentId
	 *            个人桌面内容Id
	 * @return 个人桌面内容对象
	 */
	public DesktopContent findDesktopContentByDesktopContentId(
			Long desktopContentId) {
		if (null != desktopContentId) {
			return (DesktopContent) this.getHibernateTemplate().get(
					DesktopContent.class, desktopContentId.longValue());
		} else {
			return null;
		}
	}

	/**
	 * Description: 根据查询条件获取系统信息显示的数据列表
	 * 
	 * @param prop
	 *            查询条件
	 * @param pageNum
	 *            页码
	 * @param pageSize
	 *            页数据量
	 * @return 封装了系统信息显示对象的列表
	 */
	public List findSystemMsgByCondition(Properties prop, String pageNum,
			String pageSize) {
		List list = null;
		String sql = "select ID as id,TITLE as title,STAT_SQL as statSql,PARAMS as params,STATUS as status,";
		sql += " REMARK as remark,LINK_URL as linkUrl,DATA_SOURCE as dataSource ";
		sql += " from T_JFOSS2_SYSTEM_MSG where 1=1";
		List paramList = new ArrayList();
		if (null != prop && prop.size() > 0) {
			String dstcId = prop.getProperty("dstcId");
			if (StringUtils.isNotBlank(dstcId)) {
				sql += " and DSTC_ID = ?";
				paramList.add(new Long(dstcId));
			}
			String status = prop.getProperty("status");
			if (StringUtils.isNotBlank(status)) {
				sql += " and STATUS = ?";
				paramList.add(status);
			}
		}
		sql += " order by ID";
		SQLQuery query = (SQLQuery) createSQLQuery(sql, paramList.toArray());
		query.addScalar("id", Hibernate.STRING);
		query.addScalar("title", Hibernate.STRING);
		query.addScalar("statSql", Hibernate.STRING);
		query.addScalar("params", Hibernate.STRING);
		query.addScalar("status", Hibernate.STRING);
		query.addScalar("remark", Hibernate.STRING);
		query.addScalar("linkUrl", Hibernate.STRING);
		query.addScalar("dataSource", Hibernate.STRING);
		query.setResultTransformer(Transformers
				.aliasToBean(SystemMsgBean.class));
		query.setFirstResult(NumberUtils.toInt(pageNum, 0));
		query.setMaxResults(NumberUtils.toInt(pageSize, 10));
		list = query.list();
		return list;
	}

	/**
	 * Description: 根据sql语句统计各类系统信息数量
	 * 
	 * @param strSql
	 *            sql语句
	 * @param params
	 *            参数值数组
	 * @return 统计结果
	 */
	public String findMsgStatByCondition(String strSql, Object[] params) {
		String count = "";
		SQLQuery query = (SQLQuery) this.createSQLQuery(strSql, params);
		count = query.uniqueResult().toString();
		return count;
	}
}
